# -*- coding:Utf-8 -*-
'''
Created on 25 nov. 2012

@author: fefoley
'''
import datetime
import ConfigParser
from codecs import decode

from proofs import Mail, Meeting 



def import_config(path_to_configfile):
    """
    Import the config file in a dictionary for latter use
    return config  typeof(dictionary)
    """
    parser = ConfigParser.ConfigParser()
    parser.read(path_to_configfile)
    return parser    


def import_mails(config):
    """    importer la liste des mails - décodage des lignes à faire par l'object Mail    """
    'read confil file to know where are the mail files'
    root_path = config.get('inputfiles','rootpath')
    #if root_path[0] == '"' or root_path[0] == "'": root_path = root_path[1:len(root_path)-1]  - now useless - each value on its own line
    file_paths = config.get('inputfiles','mails').split('\n')
    
    'read config file for setup variables : up/down time'
    setup = int(config.get('setuptime','mailstart'))
    setdown  = int(config.get('setuptime','mailend'))
    adh = int(config.get('setuptime','mailadherence'))
    
    'go through the files'
    lstmails = []
    for p in file_paths:
        #if p[0] == '"' or p[0] == "'": p = p[1:len(p)-1]  - now useless - each value on its own line
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            dline = decode(line, 'cp1252')    #depend on vba output
            mail = Mail(dline)                # lecture des lignes à faire par l'object
            mail.set_setup(setup, setdown, adh)
            lstmails.append(mail)   
        f.close()
    return lstmails

def import_sentmeetings(config):
    """    importer la liste des réunions - décodage des lignes à faire par l'object Meeting    """
    'read confil file to know where are the sentmeetings files'
    root_path = config.get('inputfiles','rootpath') 
    file_paths = config.get('inputfiles','meetings').split('\n')

    'read config file for setup variables : up/down time'
    setup = int(config.get('setuptime','sentmeetingstart'))
    setdown  = int(config.get('setuptime','sentmeetingend'))
    adh = int(config.get('setuptime','sentmeetingadherence'))
        
    'read config file for sender keywords'
    me = config.get('self','name')
    
    'go through the files'    
    lstsentmeetings = []
    for p in file_paths:
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines   
        for line in f:
            dline = decode(line, 'cp1252')
            sentmeeting = Meeting(dline)
            ' check if I sent it before adding it to the list'         
            if str.find(sentmeeting.getsender().lower(), me.lower()) != -1 :
                sentmeeting.set_setup(setup, setdown, adh)
                lstsentmeetings.append(sentmeeting) 
        f.close()
    return lstsentmeetings

def import_meetings(config):
    """    importer la liste des réunions - décodage des lignes à faire par l'object Meeting    """
    'read confil file to know where are the meetings files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','meetings').split('\n')

    'read config file for setup variables : up/down time'
    setup = int(config.get('setuptime','meetingstart'))
    setdown  = int(config.get('setuptime','meetingend'))
    adh = int(config.get('setuptime','meetingadherence'))    
    
    'go through the files'    
    lstmeetings = []
    for p in file_paths:
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines   
        for line in f:
            dline = decode(line, 'cp1252')   
            meeting = Meeting(dline)                # lecture des lignes à faire par l'object
            meeting.set_setup(setup, setdown, adh)                     
            lstmeetings.append(meeting) 
        f.close()
    return lstmeetings


def import_holidays(config):
    """importer la liste des jours fériés
    import csv with holyday listing assuming the following structure: 
    Date(dd/mm/yyyy)  String(nom du jour férié)
    return list of (datetime.date, strNomJourFerie)
    """ 
    'read confil file to know where are the import_holidays files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','holidays').split('\n')

    'go through the files'          
    lstholidays = []
    for p in file_paths:    
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            linesplit = line.rstrip('\n').split('\t')  # take off endofline - date+nomjourférié per line
            if len(linesplit) != 2:   # should be 2 fields
                raise Exception("format error for {}".format(linesplit))  # could be some formatting errors
            else:
                lstholidays.append((datetime.datetime.strptime(linesplit[0], "%d/%m/%Y").date(), linesplit[1]))
        f.close()                   
    return lstholidays

def import_daysoff(config):
    """
    import csv with dayoff listing
    assuming the following structure: 
    FromDate(dd/mm/yyyy) ToIncludedDate(dd/mm/yyyy) TypeOfDayoff(string) NbOfDayoff(float) 
    return list of (date, date, type, nb)
    """
    'read confil file to know where are the import_daysoff files'
    root_path = config.get('inputfiles','rootpath')  
    file_paths = config.get('inputfiles','dayoffs').split('\n')
        
    lstdayoffs = []
    for p in file_paths:      
        f = open(root_path + p, 'r')
        f.readline() #ignore head lines
        for line in f:
            linesplit = line.rstrip('\n').split('\t')  # take off endofline and split with TAB
            if len(linesplit) != 4:   # should be 4 fields
                raise Exception("format error for {}".format(linesplit))  # could be some formatting errors
            else:
                strFromDate, strToDate, strType, strNb = linesplit
                lstdayoffs.append((datetime.datetime.strptime(strFromDate, "%d/%m/%Y").date(), \
                                  datetime.datetime.strptime(strToDate, "%d/%m/%Y").date(), \
                                  strType, float(strNb)))
        f.close()
    return lstdayoffs    


def debug_output(debug_str, config):
    'read confil file to know where to output'
    root_path = config.get('outputfiles','rootpath')  
    file_path = config.get('outputfiles','debug')
    path = root_path + file_path
    f = open(path, 'w')
    f.write(debug_str)
    f.close
    
        
def output_timestrip(lst_lst_timestrip, config): 
    """
    YYYY/MM/DD    tsStart    tsEnd    encoded_Label
    """     
    'read confil file to know where to output'
    root_path = config.get('outputfiles','rootpath')  
    file_path = config.get('outputfiles','timestrip')
    path = root_path + file_path
    f = open(path, 'w')
    
    for lst_timestrip in lst_lst_timestrip:
        for ts in lst_timestrip:
            line = (ts.start.strftime("%Y/%m/%d") +
                        '\t' + ts.start.strftime("%H:%M") +
                        '\t' + ts.end.strftime("%H:%M") +
                        '\t' + ts.label.replace('\t','\\utab').replace('\n','\\ueol') +
                        '\n')
            f.write(line)
    
    f.close      
    



